package com.zmm.myyimixian.ui.activity.search.view;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.zmm.myyimixian.MyApp;
import com.zmm.myyimixian.R;
import com.zmm.myyimixian.base.BaseActivity;
import com.zmm.myyimixian.bean.SearchBean;
import com.zmm.myyimixian.bean.SearchResult;
import com.zmm.myyimixian.config.ConfigPath;
import com.zmm.myyimixian.db.DataDao;
import com.zmm.myyimixian.db.ShoppingCart;
import com.zmm.myyimixian.ui.activity.main.home.MyGridView;
import com.zmm.myyimixian.ui.activity.main.home.MyListView;
import com.zmm.myyimixian.ui.activity.search.presenter.SearchPresenterIml;
import com.zmm.myyimixian.ui.adapter.ModifyCountInterface;
import com.zmm.myyimixian.ui.adapter.SearchAdapter;
import com.zmm.myyimixian.util.UIManager;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bmob.v3.listener.DeleteListener;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

public class SearchActivity extends BaseActivity implements ISearchView,ModifyCountInterface{

    private SharedPreferences mSp;//存储对象
    private SharedPreferences.Editor mEditor;//存储器
    private ArrayAdapter<String> mHistoryAdapter;//历史记录的adapter
    private SearchAdapter mAdapter;//搜索的适配器
    private SearchPresenterIml presenterIml;//负责完成View与Model间的逻辑和交互
    private List<SearchResult> results;//网络数据商品
    private int ItemCount = 0;//默认购物车0个商品
    @BindView(R.id.search_lv_history)
    MyListView searchLvHistory;//历史记录的listView
    @BindView(R.id.search_llayout_history)
    LinearLayout searchLlayoutHistory;//历史记录的布局
    @BindView(R.id.search_et)
    EditText searchEt;//搜索输入框
    @BindView(R.id.search_scroll_null)
    ScrollView searchSceollNull;//搜索提示的视图
    @BindView(R.id.search_rlayout_content)
    RelativeLayout searchRlayoutContent;//搜索开始以后的视图
    @BindView(R.id.search_progress)
    ProgressBar searchProgress;//搜索开始显示的进度
    @BindView(R.id.search_error)
    ImageView searchError;//搜索出现异常情况显示的图片
    @BindView(R.id.search_llayout_without)
    LinearLayout searchWithout;//没有搜索到用户想搜的东西的时候显示的头部视图
    @BindView(R.id.search_llayout_moreover)
    LinearLayout searchMoreover;//搜索数据显示的尾部视图
    @BindView(R.id.search_grid)
    MyGridView searchGrid;//显示搜索结果的gridView
    @BindView(R.id.search_cart)
    ImageView searchCart;//购物车按钮
    @BindView(R.id.search_clear_btn)
    Button searchClear;//清除历史搜索的按钮
    @BindView(R.id.search_tv1)
    TextView searchTv1;
    @BindView(R.id.search_tv2)
    TextView searchTv2;
    @BindView(R.id.search_tv3)
    TextView searchTv3;
    @BindView(R.id.search_tv4)
    TextView searchTv4;
    @BindView(R.id.search_tv5)
    TextView searchTv5;
    @BindView(R.id.search_tv6)
    TextView searchTv6;
    @BindView(R.id.search_tv7)
    TextView searchTv7;
    @BindView(R.id.search_tv8)
    TextView searchTv8;


    @Override
    protected void initView() {
        //利用当前用户手机号创建对应的存储对象
        mSp = getSharedPreferences(MyApp.getUserPhone(), MODE_PRIVATE);
        mEditor = mSp.edit();
        //设置展示搜索历史的适配器
        mHistoryAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
        searchLvHistory.setAdapter(mHistoryAdapter);
        //设置展示搜索结果的适配器
        mAdapter = new SearchAdapter();
        mAdapter.setModifyCountInterface(this);
        searchGrid.setNumColumns(2);//设置列数
        searchGrid.setAdapter(mAdapter);
        popupKey();//弹出软键盘
        fillData();//显示历史搜索记录
        keyListener();//软键盘回车监听
        searchLvHistoryListener();//历史记录的listView的点击监听
        inputChangeListener();//输入文字改变的监听
        //数据与逻辑的交互
        presenterIml = new SearchPresenterIml(this);
        //显示搜索提示
        searchSceollNull.setVisibility(View.VISIBLE);
        searchRlayoutContent.setVisibility(View.GONE);//不显示搜索内容
        searchGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                SearchResult item = (SearchResult) mAdapter.getItem(position);
                if ("1".equals(item.getIs_buying_group())) {
                    //跳转到详情界面
                    UIManager.startListViewOneActivity(SearchActivity.this,item.getId());
                } else {
                    //跳转到团单
                    UIManager.startListViewActivity(SearchActivity.this,item.getId());
                }

            }
        });

    }
    //输入文字改变的监听
    private void inputChangeListener() {
        searchEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if ("".equals(searchEt.getText().toString().trim())) {
                    fillData();//更新历史记录数据
                    searchSceollNull.setVisibility(View.VISIBLE);  //显示搜索提示
                    searchRlayoutContent.setVisibility(View.GONE);//不显示搜索内容
                    //清除gridView的数据
                    mAdapter.setData(null);
                }
            }
        });
    }

    //软键盘回车监听
    private void keyListener() {
        searchEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    if ("".equals(searchEt.getText().toString().trim())) {
                        return true;
                    } else {
                        startSearch();//开始搜索
                    }
                    return true;
                }
                return false;
            }
        });
    }

    //历史记录的listView的点击监听
    private void searchLvHistoryListener() {
        searchLvHistory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String history = mHistoryAdapter.getItem(position);
                searchEt.setText(history);
                startSearch();//开始搜索
            }
        });
    }

    //开始搜索
    private void startSearch() {

        searchSceollNull.setVisibility(View.GONE);//不显示搜索提示
        searchMoreover.setVisibility(View.GONE);//不显示搜索结果的尾部视图
        searchWithout.setVisibility(View.GONE);//不显示搜索结果的头部视图
        searchRlayoutContent.setVisibility(View.VISIBLE);//显示搜索内容
        //开始搜索 关闭软键盘
        searchEt.setInputType(InputType.TYPE_NULL);
        searchEt.setInputType(InputType.TYPE_CLASS_TEXT);
        //将光标移至文字末尾
        searchEt.setSelection(searchEt.getText().toString().length());
        //将搜索的字段存起来
        mEditor.putString(searchEt.getText().toString().trim(), searchEt.getText().toString().trim());
        mEditor.apply();
        //开始获取网络数据
        presenterIml.loadData();
    }

    //查询SharedPreference对象,获取历史搜索的所有记录
    private void fillData() {
        List<String> list = new ArrayList<>();
        Map<String, ?> all = mSp.getAll();
        for (Map.Entry<String, ?> entry : all.entrySet()) {
            String name = (String) entry.getValue();
            list.add(name);
        }
        if (list.size() > 0) {
            //有历史数据就显示历史数据布局
            searchLlayoutHistory.setVisibility(View.VISIBLE);
            searchClear.setVisibility(View.VISIBLE);
        } else {
            //没有的话就不显示
            searchLlayoutHistory.setVisibility(View.GONE);
            searchClear.setVisibility(View.GONE);
        }
        //清空原有数据
        mHistoryAdapter.clear();
        mHistoryAdapter.addAll(list);
        mHistoryAdapter.notifyDataSetChanged();
    }

    //自动弹出键盘
    private void popupKey() {
        searchEt.setFocusable(true);
        searchEt.setFocusableInTouchMode(true);
        searchEt.requestFocus();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() { //让软键盘延时弹出，以更好的加载Activity
            public void run() {
                InputMethodManager inputManager = (InputMethodManager) searchEt.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);

                inputManager.showSoftInput(searchEt, 0);
            }

        }, 500);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_search;
    }


    @OnClick({R.id.search_back, R.id.search_iv_delete, R.id.search_tv1, R.id.search_tv2, R.id.search_tv3, R.id.search_tv4, R.id.search_tv5, R.id.search_tv6, R.id.search_tv7, R.id.search_tv8, R.id.search_clear_btn,R.id.search_cart,R.id.search_error})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.search_back:
                finish();//返回
                break;
            case R.id.search_iv_delete:
                searchEt.setText("");//清空
                break;
            case R.id.search_tv1:
                searchEt.setText(searchTv1.getText());
                startSearch();
                break;
            case R.id.search_tv2:
                searchEt.setText(searchTv2.getText());
                startSearch();
                break;
            case R.id.search_tv3:
                searchEt.setText(searchTv3.getText());
                startSearch();
                break;
            case R.id.search_tv4:
                searchEt.setText(searchTv4.getText());
                startSearch();
                break;
            case R.id.search_tv5:
                searchEt.setText(searchTv5.getText());
                startSearch();
                break;
            case R.id.search_tv6:
                searchEt.setText(searchTv6.getText());
                startSearch();
                break;
            case R.id.search_tv7:
                searchEt.setText(searchTv7.getText());
                startSearch();
                break;
            case R.id.search_tv8:
                searchEt.setText(searchTv8.getText());
                startSearch();
                break;
            case R.id.search_clear_btn://清除历史搜索
                mEditor.clear();
                mEditor.apply();
                fillData();//更新历史搜索记录
                break;
            case R.id.search_cart://跳转到购物车
                UIManager.startShoppingCartActivity(SearchActivity.this);
                break;
            case R.id.search_error://网络异常 点击重新加载数据
               presenterIml.loadData();
                break;

        }
    }

    //得到数据接口
    @Override
    public String getPath() {
        return ConfigPath.getSearchPath(searchEt.getText().toString().trim());
    }

    @Override
    public void addSearchBean(SearchBean searchBean) {
        if (searchBean.getSearch_result().size()>0){//得到用户搜索的数据
            searchWithout.setVisibility(View.GONE);
            results=searchBean.getSearch_result();


        }else if (searchBean.getHot_goods().size()>0){//没有得到用户搜索的数据
            searchWithout.setVisibility(View.VISIBLE);
            results=searchBean.getHot_goods();
        }
        searchMoreover.setVisibility(View.VISIBLE);
        mAdapter.setData(results);
        initData();//每次完成的时候查询数据库
    }

    @Override
    public void showLoadFailMsg() {
        //展示错误信息
        searchError.setVisibility(View.VISIBLE);
    }

    @Override
    public void showProgress() {
        //显示加载进度
        searchProgress.setVisibility(View.VISIBLE);
        //不展示错误信息
        searchError.setVisibility(View.GONE);
    }

    @Override
    public void hideProgress() {
        //不显示加载进度
        searchProgress.setVisibility(View.GONE);
    }
    //添加到购物车 或者 购物车对应物品的数量加1
    @Override
    public void doIncrease(int position, final TextView showCountView, final ImageButton jian, ImageButton jia, int count) {
        MyApp.isSJK = false;
        ItemCount = Integer.valueOf(showCountView.getText().toString());
        SearchResult result = results.get(position);
        if (ItemCount == 0) {
            ItemCount = 1;
            searchProgress.setVisibility(View.VISIBLE);
            DataDao.addShoppingCart(result.getImg(), result.getName(), result.getUnit_desc(), result.getUnit_price(), "1", result.getPromotion_img(), new SaveListener() {
                @Override
                public void onSuccess() {
                    searchProgress.setVisibility(View.GONE);
                    jian.setVisibility(View.VISIBLE);
                    showCountView.setVisibility(View.VISIBLE);
                    showCountView.setText("1");
                    mAdapter.notifyDataSetChanged();
                }

                @Override
                public void onFailure(int i, String s) {
                    searchProgress.setVisibility(View.GONE);
                    Toast.makeText(SearchActivity.this, "没有网络", Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            ++ItemCount;
            searchProgress.setVisibility(View.VISIBLE);
            final String valueOf = String.valueOf(ItemCount);
           //更新数据
            DataDao.setShoppingCart(result.getName(), valueOf,searchProgress, new UpdateListener() {
                @Override
                public void onSuccess() {
                    //更新成功
                    searchProgress.setVisibility(View.GONE);
                    showCountView.setText(valueOf);
                    mAdapter.notifyDataSetChanged();
                }

                @Override
                public void onFailure(int i, String s) {
                    //更新失败
                    searchProgress.setVisibility(View.GONE);
                    Toast.makeText(SearchActivity.this, "没有网络", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
    //购物车的数量-1 等于1的时候删除购物车
    @Override
    public void doDecrease(int position, final TextView showCountView, final ImageButton jian, ImageButton jia, int count) {
        MyApp.isSJK = false;
        String deletname = results.get(position).getName();
        ItemCount = Integer.valueOf(showCountView.getText().toString());
        --ItemCount;
        final String text = String.valueOf(ItemCount);
        if (ItemCount < 1) {
            //删除购物车数据
            searchProgress.setVisibility(View.VISIBLE);
            DataDao.deleteShoppingCart(results.get(position).getName(),searchProgress, new DeleteListener() {
                @Override
                public void onSuccess() {
                    searchProgress.setVisibility(View.GONE);
                    MyApp.isSJK = true;
                    showCountView.setText(text);
                    jian.setVisibility(View.GONE);
                    showCountView.setVisibility(View.GONE);
                    mAdapter.notifyDataSetChanged();
                }

                @Override
                public void onFailure(int i, String s) {
                    //删除失败
                    searchProgress.setVisibility(View.GONE);
                    Toast.makeText(SearchActivity.this, "没有网络", Toast.LENGTH_SHORT).show();
                }
            });

        } else {
            //购物车数据减一
            searchProgress.setVisibility(View.VISIBLE);
            DataDao.setShoppingCart(deletname, text,searchProgress, new UpdateListener() {
                @Override
                public void onSuccess() {
                    //更新成功
                    searchProgress.setVisibility(View.GONE);
                    showCountView.setText(text);
                    mAdapter.notifyDataSetChanged();
                }

                @Override
                public void onFailure(int i, String s) {
                    searchProgress.setVisibility(View.GONE);
                    Toast.makeText(SearchActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();//重新同步数据库数据
    }

    //获得购物车数据库数据
    private void initData() {
        if (MyApp.isLogin()) {
            MyApp.isSJK = true;
            searchProgress.setVisibility(View.VISIBLE);
            DataDao.getAllShoppingCarts(new FindListener<ShoppingCart>() {
                @Override
                public void onSuccess(List<ShoppingCart> list) {
                    searchProgress.setVisibility(View.GONE);
                    mAdapter.setShuJuKu(list);
                }

                @Override
                public void onError(int i, String s) {
                    searchProgress.setVisibility(View.GONE);
                    Toast.makeText(SearchActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
}
